package com.metagurukul.metagranth.actionservlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.metagurukul.metagranth.service.QuestionService;
import com.metagurukul.metagranth.vo.MetaData;

/**
 * This Servlet is responsible for getting Question Details for all the
 * questions asked so far. It will collect the metaDataList for every question.
 * 
 * @author team MetaGranth
 * 
 */
public class GetQuestionDetailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetQuestionDetailServlet() {
		super();

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * this function will get the questionId of a particular question and will
	 * get the Question Details for that particular question by calling
	 * getQuestionDetailByQuestionId() function in the service layer and will
	 * retrieve the metaDatList and will dispatch the same on the question.jsp
	 * page.
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doPerform(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		if(session.getAttribute("userId")!=null){
		try {
			// gets the questionId of the particular question
			int questionId = Integer.parseInt(request.getParameter("questionId"));
			// call the getQuestionDetailByQuestionId() function in the
			// QuestionService Service layer
			MetaData metaData = QuestionService.getQuestionDetailByQuestionId(questionId);
			request.setAttribute("metaData", metaData);
			request.getRequestDispatcher("question.jsp").forward(request,response);
		} catch (Exception exception) {
			//exception.printStackTrace();
			request.setAttribute("errormsg", exception.getMessage());
			request.getRequestDispatcher("errorPage.jsp").forward(request,response);
		}
		}else {
			response.sendRedirect("index.jsp");
		}
	}
}
